package com.huike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.constants.MessageConstant;
import com.huike.dto.*;
import com.huike.entity.*;
import com.huike.exception.BaseException;
import com.huike.mapper.*;
import com.huike.result.PageResult;
import com.huike.result.Result;
import com.huike.service.BusinessService;
import com.huike.utils.BaseContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 商机分页查询
     *
     * @param businessPageDto
     * @return
     */
    @Override
    public PageResult findPage(BusinessPageDto businessPageDto) {

        if (businessPageDto == null) {
            throw new BaseException(MessageConstant.DATA_NOT_EXIST);
        }

        if (businessPageDto.getPage() == null || businessPageDto.getPageSize() == null) {
            businessPageDto.setPage(1);
            businessPageDto.setPageSize(10);
        }

        Integer page = businessPageDto.getPage();
        Integer pageSize = businessPageDto.getPageSize();

        //姓名
        LambdaQueryWrapper<Customer> lqw = new LambdaQueryWrapper<>();
        if (businessPageDto.getName() != null) {
            lqw.like(Customer::getName, businessPageDto.getName());
        }

        //id
        if (businessPageDto.getCustomerId() != null) {
            lqw.eq(Customer::getCustomerId, businessPageDto.getCustomerId());
        }

        //手机号
        if (businessPageDto.getPhone() != null) {
            lqw.like(Customer::getPhone, businessPageDto.getPhone());
        }

        //归属人
        if (businessPageDto.getBelonger() != null) {
            lqw.like(Customer::getBelonger, businessPageDto.getBelonger());
        }

        //商机状态
        if (businessPageDto.getStatus() != null) {
            lqw.eq(Customer::getStatus, businessPageDto.getStatus());
        }

        //起止时间
        if (businessPageDto.getBeginTime() != null && businessPageDto.getEndTime() != null) {
            LocalDateTime endTime = businessPageDto.getEndTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();

            LocalDateTime beginTime = businessPageDto.getBeginTime().toInstant()
                    .atZone(ZoneId.systemDefault()).toLocalDateTime();

            lqw.between(Customer::getCreateTime, beginTime, endTime);
        }

        lqw.eq(Customer::getIsHighSea, (short) 0);
        //分页查询
        Page<Customer> customerPage = businessMapper.selectPage(new Page<>(page, pageSize), lqw);

        //封装结果集
        PageResult pageResult = new PageResult();
        pageResult.setRecords(customerPage.getRecords());
        pageResult.setTotal(customerPage.getTotal());

        return pageResult;
    }

    /**
     * 查询归属人
     *
     * @return
     */
    @Override
    public List<String> findBelonger() {

        List<Customer> customerList = businessMapper.selectList(null);
        List<String> belongerList = customerList.stream()
                .map(customer -> customer.getBelonger()).collect(Collectors.toList());

        HashSet<String> set = new HashSet<>();
        for (String belonger : belongerList) {
            set.add(belonger);
        }

        belongerList.clear();
        customerList.clear();
        belongerList.addAll(set);

        return belongerList;
    }

    /**
     * 查询商机状态
     *
     * @return
     */
    @Override
    public List<String> findStatus() {

        LambdaQueryWrapper<SysDictData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDictData::getDictType, "clue_status");
        List<SysDictData> sysDictData = sysDictDataMapper.selectList(lqw);

        return sysDictData.stream().map(s -> s.getDictLabel()).collect(Collectors.toList());
    }

    /**
     * 新建商机
     *
     * @param newCustomerDto
     */
    @Override
    public void save(NewCustomerDto newCustomerDto) {
        Customer customer = new Customer();
        BeanUtils.copyProperties(newCustomerDto, customer);

        //TODO:最后换成拦截器获取
        //Long currentId = BaseContext.getCurrentId();

        SysUser sysUser = sysUserMapper.selectById(1);

        customer.setBelonger(sysUser.getNickName());
        customer.setCreateTime(LocalDateTime.now());
        customer.setIsHighSea((short) 0);
        businessMapper.insert(customer);
    }

    /**
     * 渠道查询
     *
     * @return
     */
    @Override
    public List<String> findItem() {
        LambdaQueryWrapper<SysDictData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDictData::getDictType, "clues_item");
        List<SysDictData> sysDictData = sysDictDataMapper.selectList(lqw);

        return sysDictData.stream().map(s -> s.getDictLabel()).collect(Collectors.toList());
    }

    /**
     * 根据id查询客户资料
     *
     * @param customerId
     * @return
     */
    @Override
    public Result findById(Long customerId) {

        Customer customer = businessMapper.selectById(customerId);

        return Result.success(customer);
    }

    /**
     * 退回公海池
     *
     * @param dto
     * @return
     */
    @Override
    public Result toSea(BusinessToSeaDto dto) {
        // 查询客户数据
        Customer customer = businessMapper.selectById(dto.getCustomerId());
        customer.setReason(dto.getReason());
        customer.setIsHighSea((short) 1);
        // 修改数据
        businessMapper.updateById(customer);
        return Result.success();
    }

    /**
     * 查询理由
     *
     * @return
     */
    @Override
    public Result findReason() {

        LambdaQueryWrapper<SysDictData> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysDictData::getDictType, "reasons_for_business_reporting");
        List<SysDictData> sysDictData = sysDictDataMapper.selectList(lqw);
        List<String> stringList = sysDictData.stream().map(s -> s.getDictLabel()).collect(Collectors.toList());
        return Result.success(stringList);
    }

    /**
     * 查询所有下拉框
     *
     * @return
     */
    @Override
    public Result findAllDictData() {
        LambdaQueryWrapper<SysDictData> lqw = new LambdaQueryWrapper<>();

        Map<String, Object> map = new HashMap<>();

        // 职业下拉
        List<SysDictData> jobList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "job"));
        List<String> job = jobList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("职业", job);
        // 学历下拉
        List<SysDictData> educationList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "education"));
        List<String> education = educationList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("学历", education);
        // 所在地区
        List<SysDictData> regionList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "region"));
        List<String> region = regionList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("所在地区", region);
        // 年龄下拉
        List<SysDictData> ageList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "age"));
        List<String> age = ageList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("年龄", age);
        // 专业下拉
        List<SysDictData> majorList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "major"));
        List<String> major = majorList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("专业", major);
        // 在职情况
        map.put("在职情况", job);
        // 当前薪资
        List<SysDictData> salaryList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "salary"));
        List<String> salary = salaryList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("当前薪资", salary);
        // 目标新增
        map.put("目标薪资", salary);
        // 意向学科
        map.put("意向学科", major);
        // 意向课程
        List<SysDictData> courseSubjectList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "course_subject"));
        List<String> courseSubject = courseSubjectList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("意向课程", courseSubject);
        // 跟进状态 clue_status
        List<SysDictData> clueStatusList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "clue_status"));
        List<String> clueStatus = clueStatusList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("跟进状态", clueStatus);
        // 沟通重点 communication_point
        List<SysDictData> communicationPointList = sysDictDataMapper.selectList(lqw.eq(SysDictData::getDictType, "communication_point"));
        List<String> communicationPoint = communicationPointList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList());
        map.put("沟通重点", communicationPoint);

        return Result.success(map);
    }


    @Autowired
    private DepartmentMapper departmentMapper;


    /**
     * 分配线索部门回显
     *
     * @return
     */
    @Override
    public Result findAllDept() {

        List<Department> departments = departmentMapper.selectList(null);

        return Result.success(departments);
    }


    @Autowired
    private DeptCustomerMapper deptCustomerMapper;

    /**
     * 线索分配
     *
     * @param dto
     * @return
     */
    @Override
    public Result cueAllocation(DeptCustomerDto dto) {
        List<Long> customerIds = dto.getCustomerIds();
        if (customerIds.size() > 2) {
            throw new BaseException("保存量达到上线, 最多选择2条上商机");
        }

        for (Long customerId : customerIds) {
            DeptCustomer deptCustomer = new DeptCustomer();
            deptCustomer.setCustomerId(customerId);
            deptCustomer.setDeptId(dto.getDeptId());
            deptCustomerMapper.insert(deptCustomer);
        }

        return Result.success("操作成功");
    }

    @Autowired
    private CustomerInfoMapper customerInfoMapper;





    @Override
    public Result getById(Long id) {
        Customer customer = businessMapper.selectById(id);
        return Result.success(customer);
    }

    @Override
    public Result addRecord(CustomerInfoDto customerInfoDto) {
        List<String> focus = customerInfoDto.getFocus();
        String focus1="";
        if (focus!=null){
            for (String s : focus) {
                focus1+=focus;
            }
        }
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtils.copyProperties(customerInfoDto,customerInfo);
        customerInfo.setFocus(focus1);
        customerInfo.setCreateTime(LocalDateTime.now());
        customerInfoMapper.insert(customerInfo);
        return Result.success();
    }

    @Override
    public Result searchHistory(Long customerId) {
        LambdaQueryWrapper<CustomerInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CustomerInfo::getCustomerId,customerId);
        List<CustomerInfo> customerInfos = customerInfoMapper.selectList(lqw);
        return Result.success(customerInfos);
    }
}
